package ee.reliability.tool.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

public class CalendarHelper {

	private final List<Date> holdayList;
	private final List<Date> shortDayList;

	/*
	 * @param year the value used to set the <code>YEAR</code> calendar field.
	 *
	 */
	public int getWorkHoursInYear(int year) {
		int workHours = 0;
		Calendar cal = Calendar.getInstance();
		cal.clear();
		cal.set(year, 0, 1);
		while (cal.get(Calendar.YEAR) == year) {
			workHours += getWorkHoursInDay(cal.getTime());
			cal.add(Calendar.DATE, 1);
		}
		return workHours;
	}

	/*
	 * @param year the value used to set the <code>YEAR</code> calendar field.
	 *
	 * @param month the value used to set the <code>MONTH</code> calendar field.
	 * Month value is 0-based. e.g., 0 for January.
	 */
	public int getWorkHoursInMonth(int year, int month) {
		int workHours = 0;
		Calendar cal = Calendar.getInstance();
		cal.clear();
		cal.set(year, month, 1);
		while (cal.get(Calendar.MONTH) == month) {
			workHours += getWorkHoursInDay(cal.getTime());
			cal.add(Calendar.DATE, 1);
		}
		return workHours;
	}

	public int getWorkHoursInDay(Date date) {
		if (!isWorkDay(date))
			return 0;
		if (isShortDay(date))
			return 5;
		return 8;
	}

	public boolean isShortDay(Date date) {
		for (Date d : shortDayList)
			if (d.equals(date))
				return true;
		return false;
	}

	@SuppressWarnings("deprecation")
	public boolean isWorkDay(Date date) {
		if (date.getDay() == 0 || date.getDay() == 6)
			return false;
		for (Date d : holdayList)
			if (d.equals(date))
				return false;
		return true;
	}

	private CalendarHelper() {
		holdayList = new LinkedList<>();
		shortDayList = new LinkedList<>();
		Scanner scanner = null;
		try {
			scanner = new Scanner(new File(
					"src/main/resources/holidays.properties"));
			while (scanner.hasNextLine()) {
				String line = scanner.nextLine();
				if (line.equals("BIG_FRIDAY"))
					holdayList.add(new BigFriday());
				else
					holdayList.add(new Day(line));
			}
			scanner = new Scanner(new File(
					"src/main/resources/shortDays.properties"));
			while (scanner.hasNextLine()) {
				String line = scanner.nextLine();
				shortDayList.add(new Day(line));
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}finally{
			if(scanner != null)
				scanner.close();
		}
	}

	public static CalendarHelper getInstance() {
		return Holder.me;
	}

	private static final class Holder {
		public static final CalendarHelper me = new CalendarHelper();
	}
}
